#!/bin/bash

echo "=== 构建改进版Pub-Sub通信框架 ==="

# 设置编译器和编译选项
CXX=${CXX:-g++}
CXXFLAGS="-std=c++17 -Wall -Wextra -O2 -g"
INCLUDES="-I../include -I../third_party/boost.asio/include -I../third_party/fmt/include -I../third_party/spdlog/include"
LIBS="-lpthread -lrt"
SRCDIR="../src"

# 检查必要的依赖
echo "检查依赖..."

# 检查boost
if ! pkg-config --exists --print-errors "boost" 2>/dev/null; then
    echo "警告: 未找到系统boost，将使用third_party中的boost.asio"
fi

# 检查msgq源文件
if [ ! -f "$SRCDIR/msgq/msgq.cc" ]; then
    echo "错误: 未找到msgq源文件: $SRCDIR/msgq/msgq.cc"
    exit 1
fi

# 检查头文件
if [ ! -f "../include/msgq/msgq.h" ]; then
    echo "错误: 未找到msgq头文件: ../include/msgq/msgq.h"
    exit 1
fi

echo "依赖检查完成"

# 创建构建目录
BUILD_DIR="build"
mkdir -p $BUILD_DIR

# 编译改进版演示程序
echo "编译改进版Pub-Sub演示程序..."
$CXX $CXXFLAGS $INCLUDES \
    -o $BUILD_DIR/improved_pubsub_demo \
    improved_pubsub_demo.cpp \
    $SRCDIR/msgq/msgq.cc \
    $LIBS

if [ $? -eq 0 ]; then
    echo "✅ 编译成功: $BUILD_DIR/improved_pubsub_demo"
else
    echo "❌ 编译失败"
    exit 1
fi

# # 编译原版演示程序（作为对比）
# echo "编译原版Pub-Sub演示程序..."
# $CXX $CXXFLAGS $INCLUDES \
#     -o $BUILD_DIR/original_pubsub_demo \
#     pubsub_demo.cpp \
#     $LIBS

if [ $? -eq 0 ]; then
    echo "✅ 编译成功: $BUILD_DIR/original_pubsub_demo"
else
    echo "⚠️  原版编译失败（可能缺少依赖）"
fi

echo ""
echo "=== 构建完成 ==="
echo ""
echo "使用方法:"
echo "1. 运行改进版完整演示:"
echo "   ./$BUILD_DIR/improved_pubsub_demo"
echo ""
echo "2. 分步运行改进版:"
echo "   # 终端1: 启动注册中心"
echo "   ./$BUILD_DIR/improved_pubsub_demo registry"
echo ""
echo "   # 终端2: 启动订阅者"
echo "   ./$BUILD_DIR/improved_pubsub_demo subscriber 订阅者1 news weather"
echo ""
echo "   # 终端3: 启动发布者"
echo "   ./$BUILD_DIR/improved_pubsub_demo publisher"
echo ""
echo "3. 性能测试:"
echo "   ./$BUILD_DIR/improved_pubsub_demo perf"
echo ""
echo "4. 对比测试原版（如果编译成功）:"
echo "   ./$BUILD_DIR/original_pubsub_demo"
echo ""
echo "主要改进:"
echo "✅ 使用msgq模块进行消息存储"
echo "✅ 每个订阅者独立EventFD"
echo "✅ 修复消息竞争和丢失问题"
echo "✅ 更好的架构分离"
echo "✅ 符合原始设计意图"
